﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EndToEndSilverlightDemo.NorthWindServiceReference;
using System.IO.IsolatedStorage;
using EndtoEndSilverlightDemo.Tests;
using System.Linq.Expressions;

namespace EndToEndSilverlightDemo
{
    public partial class Page : UserControl, IPageTestDriver
    {
        ApplicationSettings settings = ApplicationSettings.Default;

        public Page()
        {            
            InitializeComponent();
            if (!settings.Contains("defaultDataGridValue"))
            {
                settings.Add("defaultDataGridValue", null);
            }
            else
            {
                dataGridResults.ItemsSource = settings["defaultDataGridValue"] as Product[];
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var client = new NorthWindServiceReference.NorthwindServiceClient();
            client.GetProductsCompleted += 
                new EventHandler<GetProductsCompletedEventArgs>(client_GetProductsCompleted);
            client.GetProductsAsync(txtProductString.Text);
        }

        void client_GetProductsCompleted(object sender, EndToEndSilverlightDemo.NorthWindServiceReference.GetProductsCompletedEventArgs e)
        {
            dataGridResults.ItemsSource = e.Result;
            settings["defaultDataGridValue"] = e.Result;
            settings.Save();
        }

        private void btnOne_MouseEnter(object sender, MouseEventArgs e)
        {
        }

        void IPageTestDriver.TypeSearchPrefix(string searchPrefix)
        {
            this.txtProductString.Text = searchPrefix;
        }

        void IPageTestDriver.ClickSearchButton()
        {
            this.Button_Click(this.btnOne,null);
        }

        int IPageTestDriver.DisplayedProductRows
        {
            get { return (new List<object>((IEnumerable<object>) this.dataGridResults.ItemsSource)).Count; }
        }

        void IPageTestDriver.ClearLocalStorage()
        {
            settings.Clear();
            settings.Save();
            dataGridResults.ItemsSource = null;
        }

        bool IPageTestDriver.WebserviceHasReturnedData()
        {
            return dataGridResults.ItemsSource != null;
        }
        
    }
}
